﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Configuration;

namespace Rdz.Utility
{
	public static class ConfigUtility
	{
		/// <summary>
		/// Writes to configuration file (App.Config) to specified key, or creates a new Key if doesn't exist
		/// </summary>
		/// <param name="KeyName">The Application Settings KeyName</param>
		/// <param name="Value">The Application Settings Value</param>
		public static void WriteToAppConfig(string KeyName, string Value)
		{
			Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
			if (cfg.AppSettings.Settings.AllKeys.Contains(KeyName))
				cfg.AppSettings.Settings[KeyName].Value = Value;
			else
				cfg.AppSettings.Settings.Add(KeyName, Value);
			cfg.Save(ConfigurationSaveMode.Modified);
			ConfigurationManager.RefreshSection("appSettings");
		}

		/// <summary>
		/// Deletes specified key in app.config
		/// </summary>
		/// <param name="KeyName"></param>
		public static void DeleteAppConfig(string KeyName)
		{
			Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
			if (cfg.AppSettings.Settings.AllKeys.Contains(KeyName))
			{
				cfg.AppSettings.Settings.Remove(KeyName);
				cfg.Save(ConfigurationSaveMode.Modified);
			}
			ConfigurationManager.RefreshSection("appSettings");
		}

		public static string GetConfig(string KeyName)
		{
			try
			{
				return ConfigurationManager.AppSettings[KeyName];
			} catch { return ""; }
		}
	}
}
